//
//  Home2ViewController.m
//  SulitLoanDemo
//
//  Created by 虞嘉伟 on 2025/2/19.
//  
  

#import "Home2ViewController.h"
#import <YYKit.h>
#import <Masonry.h>
#import <MJRefresh.h>
#import "MustLocation.h"
#import "DeviceInfo.h"
#import "OriginData.h"
#import "WiFiInfo.h"

#import "Home2Card1TableViewCell.h"
#import "RepaymentReminderTableViewCell.h"
#import "Home2Card2TableViewCell.h"
#import "SLCarouselComponent.h"
#import "SLOtherProductComponent.h"
#import "SLProductItemComponent.h"




@interface Home2ViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
/// 是否强制定位
@property (nonatomic, assign, readonly) BOOL isMustLocation;

/// 是否有还款提醒cell
@property (nonatomic, assign) BOOL hasRepaymentReminder;

@end

@implementation Home2ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self hidenNavBar];
    
    NSDictionary *cleanliness = self.homeModel[@"cleanliness"];
    NSArray *wanteds = cleanliness[@"wanted"];
    _hasRepaymentReminder = wanteds.count > 0;
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view).inset(0);
        make.top.equalTo(self.navBar.mas_bottom).inset(2);
        make.bottom.equalTo(self.view).inset(0);
    }];
    
    @weakify(self);
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self);
        [self requestDataWithCompletion:^(NSDictionary *dict) {
            @strongify(self);
            [self.tableView.mj_header endRefreshing];
            [self handleHomeDataFinish:dict];
        }];
    }];
    
    [SLLocationService startLocationWithCompletion:^(CGFloat lat, CGFloat lon) {
        @strongify(self);
        [WiFiInfo.shared getWiFiInfo:nil];
        if (lat == 0 && lon == 0) {
            // 获取定位失败
            if (self.isMustLocation) {
                // 弹出自定义弹窗
                [MustLocation openAppSettingsAlert:self];
            }
        }
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    @weakify(self);
    [self requestDataWithCompletion:^(NSDictionary *dict) {
        @strongify(self);
        [self handleHomeDataFinish:dict];
    }];
}
- (void)handleHomeDataFinish:(NSDictionary *)dict {
    NSString *peppers = [OriginData peppersOrigin:dict[@"breathe"][@"peppers"]];
    if ([peppers isEqualToString:@"LARGE_CARD"]) {
        [SLRoutePush routeMain];
    } else {
        self.homeModel = dict;
        NSDictionary *cleanliness = self.homeModel[@"cleanliness"];
        NSArray *wanteds = cleanliness[@"wanted"];
        self.hasRepaymentReminder = wanteds.count > 0;
        [self.tableView reloadData];
    }
}
- (void)requestDataWithCompletion:(void(^)(NSDictionary *dict))completion {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HomeRequestProvider requestNewHomeWithSuccess:^(NSDictionary * _Nonnull dict) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        !completion ?: completion(dict);
    } failure:^(YTKRequest * _Nonnull request) {
        !completion ?: completion(nil);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [ResponseToast showToastWithRequest:request];
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _hasRepaymentReminder ? 3 : 2;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        Home2Card1TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Home2Card1TableViewCell" forIndexPath:indexPath];
        NSDictionary *wanted = self.homeModel[@"breathe"][@"wanted"][0];
        [cell.avatar sl_setImageWithURL:wanted[@"nice"]];
        cell.productName.text = [wanted[@"chair"] description];
        cell.creditLimitMoney.text = [wanted[@"supposed"] description];
        @weakify(self);
        [cell.bgView jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
            @strongify(self);
            if ([MustLocation runableWithMustLocation:self.isMustLocation controller:self]) {
                [self jumpProductDetailWithProductID:wanted[@"didn"]];
            }
        }];
        [cell.apply jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
            @strongify(self);
            if ([MustLocation runableWithMustLocation:self.isMustLocation controller:self]) {
                [self jumpProductDetailWithProductID:wanted[@"didn"]];
            }
        }];
        return cell;
    } else if (indexPath.row == 1 && _hasRepaymentReminder) {
        // 还款提醒
        RepaymentReminderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RepaymentReminderTableViewCell" forIndexPath:indexPath];
        
        NSDictionary *cleanliness = self.homeModel[@"cleanliness"];
        NSArray *wanteds = cleanliness[@"wanted"];
        cell.carousel.stringGroup = wanteds;
        @weakify(self);
        cell.carousel.carousel.clickItemOperationBlock = ^(NSInteger index) {
            @strongify(self);
            if ([MustLocation runableWithMustLocation:self.isMustLocation controller:self]) {
                NSString *elegance = wanteds[index][@"elegance"];
                [SLRoutePush route:elegance parameter:nil];
            }
        };
        [cell.carousel setMoreButtonCallback:^(NSInteger index) {
            @strongify(self);
            if ([MustLocation runableWithMustLocation:self.isMustLocation controller:self]) {
                NSString *elegance = wanteds[index][@"elegance"];
                [SLRoutePush route:elegance parameter:nil];
            }
        }];
        return cell;
    } else {
        Home2Card2TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Home2Card2TableViewCell" forIndexPath:indexPath];
        NSArray<NSDictionary *> *wanteds = self.homeModel[@"enjoy"][@"wanted"];
        cell.items = wanteds;
        @weakify(self);
        cell.itemClickCallback = ^(NSInteger index) {
            @strongify(self);
            if ([MustLocation runableWithMustLocation:self.isMustLocation controller:self]) {
                NSDictionary *wanted = wanteds[index];
                [self jumpProductDetailWithProductID:wanted[@"didn"]];
            }
        };
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell isKindOfClass:Home2Card1TableViewCell.class]) {
        Home2Card1TableViewCell *myCell = (Home2Card1TableViewCell *)cell;
        [myCell layoutIfNeeded];
        [myCell.bgView roundTopCornerRadius:20];
    }
    if (_hasRepaymentReminder) {
        if ([cell isKindOfClass:RepaymentReminderTableViewCell.class]){
            RepaymentReminderTableViewCell *myCell = (RepaymentReminderTableViewCell *)cell;
            [myCell layoutIfNeeded];
            [myCell.bgView roundTopCornerRadius:20];
        }
    } else {
        if ([cell isKindOfClass:Home2Card2TableViewCell.class]){
            Home2Card2TableViewCell *myCell = (Home2Card2TableViewCell *)cell;
            [myCell layoutIfNeeded];
            [myCell.bgView roundTopCornerRadius:20];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (void)jumpProductDetailWithProductID:(NSString *)productId {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [ProductApplyRequestProvider requestProductApplyWithProductID:productId success:^(NSDictionary * _Nonnull dict) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSString *elegance = dict[@"elegance"];
        if (elegance.length > 0) {
            // 借款中
            [SLRoutePush route:elegance parameter:nil];
        } else {
            // 准入成功
            [SLRoutePush route:@"SLCoreCertificationViewController" parameter:@{@"productId": productId}];
        }
    } failure:^(YTKRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [ResponseToast showToastWithRequest:request];
    }];
    
    [self reportLocation];
    [self reportDevice];
    [self reportLogin];
}

- (void)reportLocation {
    [TrackLocationModel location:^(TrackLocationModel * _Nonnull model) {
        [LocationRequestProvider requestTrackWithLocation:model success:^(NSDictionary * _Nonnull dict) {
            NSLog(@"位置信息上报成功");
        } failure:^(YTKRequest * _Nonnull request) {
            NSLog(@"位置信息上报失败");
        }];
    }];
}
- (void)reportDevice {
    [DeviceRequestProvider requestTrackWithDeviceInfo:DeviceInfo.deviceInfo success:^(NSDictionary * _Nonnull dict) {
        NSLog(@"设备信息上报成功");
    } failure:^(YTKRequest * _Nonnull request) {
        NSLog(@"设备信息上报失败");
    }];
}
- (void)reportLogin {
    [SLLocationService startLocationWithCompletion:^(CGFloat lat, CGFloat lon) {
        [Analysis sendDataWithProductID:nil time:Analysis.login];
    }];
}



- (BOOL)isMustLocation {
#ifdef DEBUG
    return NO;
#endif
    // 重中之重： 强制定位字段：1强制，0不强制， 当等于1时候，点击申请需要判断是否有定位权限，没有的话不允许点击，提示去系统里设置
    return [self.homeModel[@"atom"] boolValue];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = UIColor.whiteColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 500; // 预估行高
        _tableView.insetsContentViewsToSafeArea = NO;
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        [_tableView registerClass:Home2Card1TableViewCell.class forCellReuseIdentifier:@"Home2Card1TableViewCell"];
        [_tableView registerClass:Home2Card2TableViewCell.class forCellReuseIdentifier:@"Home2Card2TableViewCell"];
        [_tableView registerClass:RepaymentReminderTableViewCell.class forCellReuseIdentifier:@"RepaymentReminderTableViewCell"];
    }
    return _tableView;
}

@end
